package com.hwhy.systemmonitoring.common.util;


import lombok.extern.slf4j.Slf4j;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;
import java.util.Objects;

/**
 * 读取服务器IP工具类
 * @author LIFULIN
 * @className IpUtil
 * @description TODO 读取服务器IP工具类
 * @date 2020/4/28-18:28
 */
@Slf4j
public class IpUtil {
    public static final String LOCAL_IP = "127.0.0.1";

    private IpUtil() {
        throw new IllegalStateException("Utility class");
    }

    /**
     * 获取服务器IP，正确的IP拿法，优先拿site-local地址
     */
    public static String getHostIp() {
        try {
            InetAddress candidateAddress = null;
            // 遍历所有的网络接口
            for (Enumeration ifaces = NetworkInterface.getNetworkInterfaces(); ifaces.hasMoreElements(); ) {
                NetworkInterface iface = (NetworkInterface) ifaces.nextElement();
                // 在所有的接口下再遍历IP
                for (Enumeration inetAddrs = iface.getInetAddresses(); inetAddrs.hasMoreElements(); ) {
                    InetAddress inetAddr = (InetAddress) inetAddrs.nextElement();
                    // 排除loopback类型地址
                    if (!inetAddr.isLoopbackAddress()) {
                        if (inetAddr.isSiteLocalAddress()) {
                            // 如果是site-local地址
                            return inetAddr.getHostAddress();
                        } else if (candidateAddress == null) {
                            // site-local类型的地址未被发现，先记录候选地址
                            candidateAddress = inetAddr;
                        }
                    }
                }
            }
            if (candidateAddress != null) {
                return candidateAddress.getHostAddress();
            }
            // 如果没有发现 non-loopback地址.只能用最次选的方案
            InetAddress jdkSuppliedAddress = InetAddress.getLocalHost();
            if (jdkSuppliedAddress == null) {
                throw new UnknownHostException("The JDK InetAddress.getLocalHost() 方法意外地返回null.");
            }
            return jdkSuppliedAddress.getHostAddress();
        } catch (Exception e) {
            UnknownHostException unknownHostException = new UnknownHostException(
                    "无法确定局域网地址: " + e);
            unknownHostException.initCause(e);
            try {
                throw unknownHostException;
            } catch (UnknownHostException hostException) {
                hostException.printStackTrace();
            }
        }
        return "127.0.0.1";
    }

    /**
     * 获取本机的内网ip地址
     */
    public static String getInet4Address() {
        try {
            //获取所有网络接口
            Enumeration<NetworkInterface> allNetworkInterfaces = NetworkInterface.getNetworkInterfaces();
            //遍历所有网络接口
            while (allNetworkInterfaces.hasMoreElements()) {
                NetworkInterface networkInterface = allNetworkInterfaces.nextElement();
                //如果此网络接口为 回环接口 或者 虚拟接口(子接口) 或者 未启用 或者 描述中包含VM
                if (networkInterface.isLoopback() || networkInterface.isVirtual() || !networkInterface.isUp() || networkInterface.getDisplayName().contains("VM")) {
                    //继续下次循环
                    continue;
                }
                /*//如果不是Intel与Realtek的网卡
                if (!(networkInterface.getDisplayName().contains("Intel")) && !(networkInterface.getDisplayName().contains("Realtek"))) {
                    //继续下次循环
                    continue;
                }*/
                //遍历此接口下的所有IP（因为包括子网掩码各种信息）
                for (Enumeration<InetAddress> inetAddressEnumeration = networkInterface.getInetAddresses(); inetAddressEnumeration.hasMoreElements(); ) {
                    InetAddress inetAddress = inetAddressEnumeration.nextElement();
                    //如果此IP不为空
                    if (inetAddress != null) {
                        //如果此IP为IPV4 则返回
                      /*  if (inetAddress instanceof Inet4Address) {
                            return inetAddress;
                        }*/
                        // -------这样判断IPV4更快----------
                        if (inetAddress.getAddress().length == 4) {
                            return Objects.requireNonNull(inetAddress).getHostAddress();
                        }
                    }
                }
            }
            return null;
        } catch (SocketException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取服务器名称
     *
     * @return
     */
    public static String getHostName() {
        try {
            return InetAddress.getLocalHost().getHostName();
        } catch (UnknownHostException e) {
            log.error(e.getMessage(), e);
        }
        return "未知";
    }


}
